package com.example.bookreader;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;


import com.example.bookreader.base.DownloadUtil;
import com.example.bookreader.base.http.EngineCallBack;
import com.example.bookreader.base.http.HttpUtils;
import com.example.bookreader.base.http.OkHttpEngine;
import com.google.gson.Gson;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import okhttp3.Response;


public class BookListActivity extends AppCompatActivity {

    private static final String TAG = "BookListActivity";
    private ListView mListView;
    private List<BookListResult.Book> mBooks = new ArrayList<>();


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_list);


        mListView = (ListView) findViewById(R.id.book_list_view);
        String url = "https://www.imooc.com/api/teacher?type=10";
        HttpUtils.init(new OkHttpEngine());
        HttpUtils.with(this).cache(false).url(url).get().execute(new EngineCallBack() {
            @Override
            public void onPreExecute(Context context, Map<String, Object> params) {

            }

            @Override
            public void onError(Exception e) {

            }

            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                BookListResult bookListResult = gson.fromJson(result, BookListResult.class);

                mBooks = bookListResult.getData();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mListView.setAdapter(new BookListAdapter());
                    }
                });
            }

            @Override
            public void onDownFileSuccess(Response inputStream) {

            }
        });
    }

    public static void start(Context context) {
        Intent intent = new Intent(context, BookListActivity.class);
        context.startActivity(intent);
    }

    private class BookListAdapter extends BaseAdapter {


        @Override
        public int getCount() {
            return mBooks.size();
        }

        @Override
        public Object getItem(int i) {
            return mBooks.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int position, View view, ViewGroup viewGroup) {
            final BookListResult.Book book = mBooks.get(position);

            ViewHolder viewHolder = new ViewHolder();
            if (view == null) {
                view = getLayoutInflater().inflate(R.layout.item_book_list_view, null);
                viewHolder.mNameTextView = view.findViewById(R.id.name_text_view);
                viewHolder.mButton = view.findViewById(R.id.book_button);
                view.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) view.getTag();
            }

            viewHolder.mNameTextView.setText(book.getBookname());
//            final String path = Environment.getExternalStorageDirectory() + "/imooc/" + book.getBookname() + ".txt";
            final File rootfile = new File(getFilesDir().toString() + File.separator + "imooc");
            if (!rootfile.exists()) {
                rootfile.mkdirs();
            }

            final File file = new File(getFilesDir().toString() + File.separator + "imooc" + File.separator + book.getBookname() + ".txt");


//            final File file = new File(path);
            viewHolder.mButton.setText(file.exists() ? "打开阅读" : "点我下载");

            final ViewHolder finalViewHolder = viewHolder;
            viewHolder.mButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(final View view) {
//                     ä¸‹è½½çš„åŠŸèƒ?
                    if (file.exists()) {
                        BookActivity.start(BookListActivity.this, file.getPath());
                    } else {
                        HttpUtils
                                .with(BookListActivity.this)
                                .cache(false)
                                .download()
                                .url(book.getBookfile())
                                .execute(new EngineCallBack() {
                                    @Override
                                    public void onPreExecute(Context context, Map<String, Object> params) {
                                    }

                                    @Override
                                    public void onError(Exception e) {
                                        finalViewHolder.mButton.setText("下载失败");
                                    }

                                    @Override
                                    public void onSuccess(String result) {

                                    }

                                    @Override
                                    public void onDownFileSuccess(Response response) {
                                        byte[] buf = new byte[2048];
                                        int len = 0;
                                        try (InputStream is = Objects.requireNonNull(response.body()).byteStream();
                                             FileOutputStream fos = new FileOutputStream(file);) {
                                            long total = response.body().contentLength();
                                            long sum = 0;
                                            while ((len = is.read(buf)) != -1) {
                                                fos.write(buf, 0, len);
                                                sum += len;
                                                int progress = (int) (sum * 1.0f / total * 100);
                                                finalViewHolder.mButton.setText(progress + "");
                                            }
                                            fos.flush();
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                        finalViewHolder.mButton.setText("立即阅读");
                                    }

                                });
                    }
                }
            });
            return view;
        }

        class ViewHolder {
            public TextView mNameTextView;
            public Button mButton;
        }
    }


    String[] permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    List<String> mPermissionList = new ArrayList<>();

    // private ImageView welcomeImg = null;
    private static final int PERMISSION_REQUEST = 1;
    // 检查权限

    private void checkPermission() {
        mPermissionList.clear();

        //判断哪些权限未授予
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permissions[i]);
            }
        }
        /**
         * 判断是否为空
         */
        if (mPermissionList.isEmpty()) {//未授予的权限为空，表示都授予了

        } else {//请求权限方法
            String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);//将List转为数组
            ActivityCompat.requestPermissions(this, permissions, PERMISSION_REQUEST);
        }
    }

    /**
     * 响应授权
     * 这里不管用户是否拒绝，都进入首页，不再重复申请权限
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case PERMISSION_REQUEST:

                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
                break;
        }
    }
}
